var HSMapView = {};
HSMapView.Prefs = HSMapView.Prefs || {};
HSMapView.Prefs.delta = 0.01;

var KOORDINATE = require('Koordinate');
var WSCALLER = require('WSCaller');
var KOORDINATE = require('Koordinate');

var LinienTyp_BUS = 1 << 1;
var LinienTyp_SBAHN = 1 << 2;
var LinienTyp_UBAHN = 1 << 3;
var LinienTyp_ZAHNRAD = 1 << 4;

function WSMap(uniqueID, pCurrentWindow) {

	if (uniqueID == undefined) {
		alert('uniqueID is null. IllegalAgrumentException');
		return
	}
	this.uniqueID = '' + uniqueID;

	this.ButtonScrollView = {};

	this.LastReginChangedEvent = 0;

	this.Annotations = {};

	this.currentPosition = {};

	this.currentWindow = pCurrentWindow;
	
	this.lastAnnoClick = 0; 
	
	this.mapView = Titanium.Map.createView({
		mapType : Titanium.Map.STANDARD_TYPE,
		region : {
			latitude : 48.731016,
			longitude : 9.253851,
			latitudeDelta : HSMapView.Prefs.delta,
			longitudeDelta : HSMapView.Prefs.delta
		},
		animate : true,
		regionFit : true,
		userLocation : true,
		annotations : [],
		visible : true
	});


	Ti.Geolocation.Android.manualMode = true;
	this.gpsProvider = Ti.Geolocation.Android.createLocationProvider({
		name : Ti.Geolocation.PROVIDER_GPS,
		minUpdateTime : 10,
		minUpdateDistance : 1
	});

	Ti.Geolocation.Android.addLocationProvider(this.gpsProvider);

	this.locationHandlerAdded = false;

	if (Ti.Geolocation.locationServicesEnabled) {

		Ti.Android.currentActivity.activWSMapObject = this;

		this.addLocationHandler();

		Ti.Android.currentActivity.addEventListener('destroy', this.removeLocationHandler);
		Ti.Android.currentActivity.addEventListener('pause', this.removeLocationHandler);
		Ti.Android.currentActivity.addEventListener('resume', this.addLocationHandler);

	} else {
		alert('Please enable location services');
	}

	this.mapView.addEventListener('complete', function(e) {
		Ti.API.info('complete');
		Ti.API.info(e);
	});
	this.mapView.addEventListener('error', function(e) {
		Ti.API.info('error');
		Ti.API.info(e);
	});
	this.mapView.addEventListener('loading', function(e) {
		Ti.API.info('loading');
		Ti.API.info(e);
	});

	this.mapView.addEventListener('regionChanged', this.regionChanged)

	this.currentWindow.addEventListener('click', this.annoClicked);

	this.CurrentRegion = {};

	this.callBack = {

		Refback : this,
		// function called when the response data is available
		onload : function(e) {

			Ti.API.info("Enter HTTPClient.onLoad. Received text: " + this.responseText);
			if(this.Refback.activityIndicator != undefined)
			{
				this.Refback.activityIndicator.hide();
			}
			this.Refback.handleHaltestellen(this.responseText);
		},
		// function called when an error occurs, including a timeout
		onerror : function(e) {
			Ti.API.debug(e.error);
			if(this.Refback.activityIndicator != undefined)
			{
				this.Refback.activityIndicator.hide();
			}

		},
		timeout : 45000 ,// in milliseconds
		
		onreadystatechange: function()
		{
			//Ti.API.info("______________________readystate:" + this.readyState)
		},
		
		ondatastream : function(e)
		{
			//Ti.API.info("ondatastream:" + JSON.stringify(e));
		}
	}

	this.client = Ti.Network.createHTTPClient(this.callBack);

}
/*
 **************************************************
 **************************************************
 *
 *   cannoClicked
 *
 **************************************************/
WSMap.prototype.annoClicked = function(evt) {

	var THIS = Ti.Android.currentActivity.activWSMapObject;

	evt = evt || {};
	
	if(new Date().getTime()-THIS.lastAnnoClick < 100)
	{
		//return;
	}
	
	//THIS.currentWindow.addEventListener('click', THIS.annoClicked);
	
	if (evt.hasOwnProperty('clicksource')) {
		if (evt.clicksource === 'pin') {

		  //  THIS.lastAnnoClick = new Date().getTime();

			//Ti.API.info("REMOVE EVENT LISTENER");
			//THIS.currentWindow.removeEventListener('click', THIS.annoClicked);

			
				Ti.API.info('PIN:' + evt.annotation.title + '    ' + THIS.uniqueID);
				Ti.API.info("Handle anno ANNO");
				//THIS.hideButtons();
				//evt.annotation.latitude
				//evt.annotation.longitude
				THIS.center2Location(evt.annotation.longitude, evt.annotation.latitude);
			
				evt.annotation.annoCaller.printHSIDs();
				
				evt.annotation.annoCaller.createAbfahrtsLines();
			
		
	
		}
Ti.API.info(evt.clicksource + ":" );
	}

}

WSMap.prototype.removeAnnoEventHandler = function() {
	var THIS = Ti.Android.currentActivity.activWSMapObject;
	Ti.API.info("REMOVE ANNO EVENT LISTENER-");

	THIS.currentWindow.removeEventListener('click', THIS.annoClicked);

}

WSMap.prototype.addAnnoEventHandler = function() {
	var THIS = Ti.Android.currentActivity.activWSMapObject;
	Ti.API.info("ADD ANNO EVENT LISTENER");

	THIS.currentWindow.addEventListener('click', THIS.annoClicked);

}



WSMap.prototype.createButtons = function(win) {

	Ti.API.info("Add button");

	var THIS = Ti.Android.currentActivity.activWSMapObject;

	THIS.ButtonScrollView = Ti.UI.createScrollView({
		contentWidth : 'auto',
		contentHeight : 'auto',
		showVerticalScrollIndicator : false,
		showHorizontalScrollIndicator : false,
		left : 4,
		top : 4,
		height : 57 + 2 * 4,
		width : 5 * 57 + 3 * 4, // 2 Buttons
		backgroundColor : '#333333',
		scrollType : 'horizontal',
		opacity : 0.4,
		borderRadius : 5
	});

	var RefreshButton = Titanium.UI.createButton({
		title : '',
		left : 4,
		top : 4,
		width : 57,
		height : 57,
		backgroundImage : 'images/button/refresh_57_57.png',		
		backgroundSelectedImage : 'images/bus_32_32.png',
		opacity : 0.8,
	});

	var MyLocationButton = Titanium.UI.createButton({
		title : '',
		left : 4 + 57 + 8,
		top : 4,
		width : 57,
		height : 57,
		backgroundImage : 'images/button/mylocation_57_57.png',
		backgroundSelectedImage : 'images/bus_32_32.png',
		opacity : 0.8,
	});



	

	THIS.ButtonScrollView.add(RefreshButton);
	THIS.ButtonScrollView.add(MyLocationButton);

	win.add(THIS.ButtonScrollView);

	MyLocationButton.addEventListener('click', THIS.center2MyLocation);
	RefreshButton.addEventListener('click', THIS.refreshAnnos);
	RefreshButton.addEventListener('longpress', THIS.refreshALLAnnos);

}

WSMap.prototype.handleHaltestellen = function(JSONStr1) {

	this.getCurrentPosition();

	Ti.API.info("Response:" + JSONStr1);

	var data1 = eval('(' + JSONStr1 + ')');

	for (var i = 0; i < data1.halteStellen.length; i++) {

		var hs = data1.halteStellen[i];

		var lngX = hs.koordinate.longitude;
		var latY = hs.koordinate.latitude;
		var title = hs.title;
		var haltestelleTyp = hs.halteStelleTyp;
		this.createAnnotaton(lngX, latY, title, haltestelleTyp, hs.allIDs.BAHN);

	}
}

WSMap.prototype.getCurrentPosition = function() {

	Titanium.Geolocation.getCurrentPosition(function(e) {
		var THIS = Ti.Android.currentActivity.activWSMapObject;

		if (e.error) {
			alert('HFL cannot get your current location');
			// TODO in Status message line
			this.currentPosition = {};
			return;
		}

		THIS.currentPosition = {
			longi : e.coords.longitude,
			latti : e.coords.latitude
		};

		/*
		 var altitude = e.coords.altitude;
		 var heading = e.coords.heading;
		 var accuracy = e.coords.accuracy;
		 var speed = e.coords.speed;
		 var timestamp = e.coords.timestamp;
		 var altitudeAccuracy = e.coords.altitudeAccuracy;
		 */

		Ti.API.info("Current Position:" + THIS.currentPosition.longi + ":" + THIS.currentPosition.latti);

	});
}

WSMap.prototype.createAnnotaton = function(lngX, latY, pTitle, pHalteStelleTyp, pHSIDs) {

	//Ti.API.info('create Anno. long:' + lngX + '  latt:' + latY);

	var hashKey = ('X' + (Math.round(lngX * 100000) / 100000) + (Math.round(latY * 100000) / 100000)).replace(/\./, '').replace(/\./, '')

	if (this.Annotations.hasOwnProperty(hashKey)) {
		Ti.API.info("################################## Already Exists: '" + hashKey + "' do nothing.");

		//this.mapView.removeAnnotation(hashKey);

		// this.mapView.removeAnnotation(this.Annotations[hashKey]);

		//delete this.Annotations[hashKey];
		this.mapView.show();
		return;
	}

	Ti.API.info("++++++++++++++++++++++++++++++++ Create ANNO: '" + hashKey);

	this.Annotations[hashKey] = Ti.Map.createAnnotation({
		latitude : latY,
		longitude : lngX,
		//title : hashKey,
		//subtitle : 'Mountain View, CA',
		animate : true,
		pincolor : Ti.Map.ANNOTATION_RED,
		//leftButton: 'KS_nav_ui.png'
		//leftView: annoview
		image : getAnnotationImageName(pHalteStelleTyp),
		hstype : pHalteStelleTyp
	});

	var A = this.Annotations[hashKey];

	var distance = '';
	if (this.currentPosition.hasOwnProperty('longi')) {
		//Distance(47.731016,9.253851 , 47.731016, 8.253851 );
		distance = Math.floor(KOORDINATE.Distance(latY, lngX, this.currentPosition.latti, this.currentPosition.longi));
		Ti.API.info("Distance:" + distance);
	};

	var httpCaller = new WSCALLER(A, pHSIDs, pHalteStelleTyp, pTitle, distance + '');

	httpCaller.createSkeleton();

	A.annoCaller = httpCaller;

	this.mapView.addAnnotation(A);
	this.mapView.show();
}

WSMap.prototype.refreshAnnos = function() {

	var THIS = Ti.Android.currentActivity.activWSMapObject;

	Ti.API.info('Current Region:' + JSON.stringify(THIS.CurrentRegion));

	var URL = 'http://geolessiprovider.appspot.com/geths?x=' + THIS.CurrentRegion.longi + '&y=' + THIS.CurrentRegion.latti + '&spanx=' + THIS.CurrentRegion.longDelta + '&spany=' + THIS.CurrentRegion.latDelta;

	Ti.API.info("Request:" + URL);

	THIS.activityIndicator = Ti.UI.createActivityIndicator({
		color : 'grey',
		font : {
			fontFamily : 'Helvetica Neue',
			fontSize : 26,
			fontWeight : 'bold'
		},
		message : 'Hole Haltestellen...',
		style : Ti.UI.iPhone.ActivityIndicatorStyle.BIG_DARK,
		top : 70,
		left : 10,
		height : 'auto',
		width : 'auto'
	});

	THIS.activityIndicator.show();

	THIS.client.open("GET", URL);
	THIS.client.send();

	// Ti.API.info("Refresh Annos:" + THIS.mapView.size.width);

}
/*
 **************************************************
 **************************************************
 *
 *   refreshALLAnnos
 *
 **************************************************/
WSMap.prototype.refreshALLAnnos = function() {
	Ti.API.info('clear all annos');
	var THIS = Ti.Android.currentActivity.activWSMapObject;
	THIS.lastAnnoClick = 0;
	THIS.Annotations = {};
	THIS.mapView.removeAllAnnotations();
	THIS.mapView.removeAllAnnotations();
	THIS.refreshAnnos();
}

/*
 **************************************************
 **************************************************
 *
 *   center2MyLocation
 *
 **************************************************/
WSMap.prototype.center2MyLocation = function() {

	var X = function(e) {
		var THIS = Ti.Android.currentActivity.activWSMapObject;
		if (e.error) {
			alert('HFL cannot get your current location');
			// TODO in Status message line
			this.currentPosition = {};
			return;
		}
		THIS.currentPosition = {
			longi : e.coords.longitude,
			latti : e.coords.latitude
		};

		if (THIS.currentPosition.hasOwnProperty('longi')) {
			var region = {
				latitude : THIS.currentPosition.latti,
				longitude : THIS.currentPosition.longi,
				animate : true,
				latitudeDelta : THIS.CurrentRegion.latDelta,
				longitudeDelta : THIS.CurrentRegion.longDelta
			};
			THIS.mapView.setLocation(region);
		}
	}
	Titanium.Geolocation.getCurrentPosition(X);
}

/*
 **************************************************
 **************************************************
 *
 *   center2Location
 *
 **************************************************/

WSMap.prototype.center2Location = function(lng, lat) {

	// nur in X-Richtung zentrieren. y bleibt
	var THIS = Ti.Android.currentActivity.activWSMapObject;
	if (THIS.mapView != undefined) {
		var region = {
			latitude : THIS.CurrentRegion.latti,
			longitude : lng,
			animate : true,
			latitudeDelta : THIS.CurrentRegion.latDelta,
			longitudeDelta : THIS.CurrentRegion.longDelta
		};
		try
		{
		THIS.mapView.setLocation(region);
		}catch(er){;}
	}
}






WSMap.prototype.regionChanged = function(e) {

	var THIS = Ti.Android.currentActivity.activWSMapObject;
	var now = new Date().getTime();

	THIS.LastReginChangedEvent = new Date().getTime();
	
	/*
	Ti.API.info('regionChanged LONG:' + e.longitude);
	Ti.API.info('regionChanged LATI:' + e.latitude);
	Ti.API.info('Span LONG X:' + e.longitudeDelta);
	Ti.API.info('Span LATI Y:' + e.latitudeDelta);
	*/
	var xspanM = KOORDINATE.Distance(e.latitude, e.longitude, e.latitude, e.longitude + e.longitudeDelta);

	Ti.API.info(xspanM + ":" + Ti.Platform.displayCaps.platformWidth);

	var xratio = Ti.Platform.displayCaps.platformWidth / xspanM;

	Ti.API.info(xratio);

	var level = "L2";
	// l5=gross, L1 = klein

	if (xratio > 2) {
		level = 'L5';
	} else if (xratio > 1.4) {
		level = 'L4';
	} else if (xratio > 0.6) {
		level = 'L3';
	} else if (xratio > 0.28) {
		level = 'L2';
	} else {
		level = 'L1';
	}

	Ti.API.info(level);

	var oldLevel = THIS.CurrentRegion.Level || 'L3';

	THIS.CurrentRegion = {
		longi : e.longitude,
		latti : e.latitude,
		longDelta : e.longitudeDelta,
		latDelta : e.latitudeDelta,
		Level : level
	};

	if (oldLevel !== level) {
		// Anno-Image anpassen
		Ti.API.info('Level-Change:' + oldLevel + '-->' + level);

		for (var anno in THIS.Annotations) {

			if (!THIS.Annotations.hasOwnProperty(anno)) {
				continue;
			}
			//Ti.API.info(typeof anno);
			Ti.API.info(THIS.Annotations[anno].image);

			// THIS.Annotations[anno].image=getAnnotationImageName(THIS.Annotations[anno].hstype);

			THIS.Annotations[anno].setImage(getAnnotationImageName(THIS.Annotations[anno].hstype, level));

		}

	} else {
		// Keine AnnoImage Aenderung
	}

}

WSMap.prototype.handleLocationChange = function(longitude, latitude) {

	Ti.API.info('handleLocationChange:' + longitude + ' : ' + latitude);

}

WSMap.prototype.handleLocation = function(e) {
	if (!e.error) {

		var THIS = Ti.Android.currentActivity.activWSMapObject;

		var longitude = e.coords.longitude;
		var latitude = e.coords.latitude;
		var altitude = e.coords.altitude;
		var heading = e.coords.heading;
		var accuracy = e.coords.accuracy;
		var speed = e.coords.speed;
		var timestamp = e.coords.timestamp;
		var altitudeAccuracy = e.coords.altitudeAccuracy;

		Ti.API.info('Location Callback:' + longitude + ' : ' + latitude + ":" + accuracy);

		THIS.handleLocationChange(longitude, latitude);

	} else {
		Ti.API.info('Error handleLocation:' + e.error);
	}

};

WSMap.prototype.addLocationHandler = function(ev) {
	Ti.API.info('Resume');

	var THIS = Ti.Android.currentActivity.activWSMapObject;

	if (!THIS.locationHandlerAdded) {
		Ti.Geolocation.addEventListener('location', THIS.handleLocation);
		THIS.locationHandlerAdded = true;
		Ti.API.info('Add Location-Handler');
	}

};

WSMap.prototype.removeLocationHandler = function() {
	Ti.API.info('Pause or Destroy');

	var THIS = Ti.Android.currentActivity.activWSMapObject;

	if (THIS.locationHandlerAdded) {
		Ti.Geolocation.removeEventListener('location', THIS.handleLocation);
		THIS.locationHandlerAdded = false;
		Ti.API.info('Remove Location-Handler');
	}
};

WSMap.prototype.getView = function() {
	return this.mapView;
}


function getAnnotationImageName(pHalteStellenType, pLevel) {

	/*
	 var LinienTyp_BUS = 1 << 1;
	 var LinienTyp_SBAHN = 1 << 2;
	 var LinienTyp_UBAHN = 1 << 3;
	 v		ar LinienTyp_ZAHNRAD = 1 << 4;
	 */
	var base = '';

	var Level = pLevel || 'L2';
	
	Ti.API.info(Level + ' -> ' + pHalteStellenType + ":" + (pHalteStellenType & LinienTyp_UBAHN & LinienTyp_BUS));

	if (pHalteStellenType == LinienTyp_BUS) {
		base = 'images/hsannos/' + Level +'/hsbus.png';
	} else if (pHalteStellenType == LinienTyp_SBAHN) {
		base = 'images/hsannos/' + Level +'/hssbahn.png';
	} else if (pHalteStellenType == LinienTyp_UBAHN) {
		base = 'images/hsannos/' + Level +'/hsubahn.png';
	} else if ((pHalteStellenType | LinienTyp_UBAHN | LinienTyp_BUS) == (LinienTyp_UBAHN | LinienTyp_BUS)) {
		base = 'images/hsannos/' + Level +'/hsubahnbus.png';
	} else if ((pHalteStellenType | LinienTyp_SBAHN | LinienTyp_BUS) == (LinienTyp_SBAHN | LinienTyp_BUS)) {
		base = 'images/hsannos/' + Level +'/hssbahnbus.png';
	} else {
		base = 'images/404';
		//todo: "Imgage not found"-Image anlegen
	}

	

	return base;
}


module.exports = WSMap;

